package com.tomecode.tools.maven.settings.parser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 
 * XML factory
 * 
 * @author Tomas Frastia
 * @see http://www.tomecode.com or
 *      http://code.google.com/p/maven-settings-editor/
 * 
 */
public final class XmlFactory {

	private static SAXReader saxReader;

	private XmlFactory() {

	}

	/**
	 * create singleton {@link SAXReader}
	 * 
	 * @return
	 */
	private final static SAXReader getSaxReader() {
		if (saxReader == null) {
			saxReader = new SAXReader();
			saxReader.setValidation(false);
		}
		return saxReader;
	}

	/**
	 * create {@link Document} from file
	 * 
	 * 
	 * @param file
	 * @return
	 * @throws DocumentException
	 */
	public final static Document parse(File file) throws DocumentException {
		return getSaxReader().read(file);
	}

	/**
	 * create new {@link Document} with encoding UTF-8
	 * 
	 * @return
	 */
	public final static Document newDocument() {
		Document doc = DocumentFactory.getInstance().createDocument();
		doc.setXMLEncoding("UTF-8");
		return doc;
	}

	/**
	 * save {@link Document} to file
	 * 
	 * @param document
	 * @param file
	 */
	public final static void xmlToFile(Document document, File file) {
		FileOutputStream fos = null;
		XMLWriter writer = null;
		try {

			if (!file.exists()) {
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setSuppressDeclaration(true);
			writer = new XMLWriter(fos, format);
			writer.write(document);
			writer.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * create element with text
	 * 
	 * @param qName
	 * @param value
	 * @param namespace
	 * @return
	 */
	public static final Element createElement(String qName, String value, Namespace namespace) {
		Element element = DocumentHelper.createElement(new QName(qName, namespace));
		element.setText(value);
		return element;
	}

}
